package proxy;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.jxta.exception.PeerGroupException;
import net.jxta.platform.NetworkManager;
import net.jxta.socket.JxtaMulticastSocket;
import overlay.OverlayManager;

public class ProxyMain {
	
	private static List<String> getMulticastGroups() {
		List<String> groups = new ArrayList<String>();
		
		groups.add("224.5.5.1:27000");
		
		return groups;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		List<Thread> sniffers = new ArrayList<Thread>();
		NetworkManager networkManager = null;
		try {
			networkManager = startJxta();
		} catch (Exception e) {
			System.err.println("Error connecting to overlay");
			e.printStackTrace();
			return;
		}
		
		JxtaMulticastSocket  mcastSocket = null;
		try {
			mcastSocket = new JxtaMulticastSocket(networkManager.getNetPeerGroup(), OverlayManager.getSocketAdvertisement());
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}
		
		OverlayListener listener = new OverlayListener(networkManager, mcastSocket);
		listener.start();
		
		for (String group : ProxyMain.getMulticastGroups()) {
			
			MulticastSniffer ms = new MulticastSniffer(group, networkManager, mcastSocket);
			ms.start();
			sniffers.add(ms);			
		}
		
		wait_thread(listener);		
		for (Thread threadSniffer : sniffers) {
			wait_thread(threadSniffer);
		}

	}

	private static void wait_thread(Thread t1) {
		try {
			t1.join();
		} catch (InterruptedException e) {
			System.err.println("Exception waiting for thread.");
		}
	}

	private static NetworkManager startJxta() throws IOException, PeerGroupException {
        NetworkManager manager = null;

        manager = new NetworkManager(NetworkManager.ConfigMode.EDGE, "ProxyMain", new File(new File(".cache"), "ProxyMain").toURI());
        System.out.println("Starting JXTA");
        manager.startNetwork();
        System.out.println("JXTA Started");
        
        return manager;
	}

}
